package com.jfsnpm.common;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class MenuTree4Auth {
	public String tsid;
	public List<MenuTree4Auth> children;
	public boolean checked=false;
	
	/**
	 * 保存树	
	 * @return this
	 */
	public boolean saveTree4Auth(String roleid){
		Record tree;
		if(StringUtils.isBlank(tsid)){
			return false;
		}
		if(StringUtils.isBlank(roleid)){
			return false;
		}
		
		if(children != null&&children.size()>0){
			for(int  i = 0   ; i < children.size(); i++) {
				if(!children.get(i).saveTree4Auth(roleid)) return false;
			}
		}
		
		tree = Db.findFirst(AppSql.getsql("pm.PmRelationMenuRoleSelect"), tsid , roleid);
		if(checked){
			if(tree == null){
				Record data = new Record().set("menuid", tsid).set("roleid", roleid);
				return Db.save("pm_relation_menu_role", data);
			}
		}else{
			if(tree!=null){
				if(Db.update(AppSql.getsql("pm.PmRelationMenuRoleDelete"), tsid,roleid) > 0){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * FOR Org Save
	 * @param roleid
	 * @return
	 */
	public boolean saveTree4Auth4Org(String roleid){
		Record tree;
		if(StringUtils.isBlank(tsid)){
			return false;
		}
		if(StringUtils.isBlank(roleid)){
			return false;
		}
		
		if(children != null&&children.size()>0){
			for(int  i = 0   ; i < children.size(); i++) {
				if(!children.get(i).saveTree4Auth4Org(roleid)) return false;
			}
		}
		
		tree = Db.findFirst(AppSql.getsql("pm.PmRelationRoleOrgSelect"), tsid , roleid);
		if(checked){
			if(tree == null){
				Record data = new Record().set("orgid", tsid).set("roleid", roleid);
				return Db.save("pm_relation_role_org", data);
			}
		}else{
			if(tree!=null){
				if(Db.update(AppSql.getsql("pm.PmRelationRoleOrgDelete"), tsid,roleid) > 0){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	/**
	 * FOR Process Save
	 * @param processid
	 * @return
	 */
	public boolean saveTree4Auth4Process(String processid){
		Record tree;
		if(StringUtils.isBlank(tsid)){
			return false;
		}
		if(StringUtils.isBlank(processid)){
			return false;
		}
		
		if(children != null&&children.size()>0){
			for(int  i = 0   ; i < children.size(); i++) {
				if(!children.get(i).saveTree4Auth4Process(processid)) return false;
			}
		}
		
		tree = Db.findFirst(AppSql.getsql("pm.PmRelationProcessOrgSelect"), tsid , processid);
		if(checked){
			if(tree == null){
				Record data = new Record().set("orgid", tsid).set("processid", processid);
				return Db.save("pm_relation_process_org", data);
			}
		}else{
			if(tree!=null){
				if(Db.update(AppSql.getsql("pm.PmRelationProcessOrgDelete"), tsid,processid) > 0){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	
	
}
